import { queryEnumerationNameList, queryEnumerationValuesList } from '@/api/base/enumeration.js'
import { queryTreeData, renderTreeNodes } from '@/api/base/ha_depart'
import json from '../../components/k-form-design/packages/KFormDesign/config/cascadeData.js'

const form = {
  state: {
    formData: {
      enumList: [], // 枚举名列表
      dynamicDataList: { 
        ad: json.cascadeData.city,
        ad4: json.cascadeData.cityLV4,
        ad4jx: []
    }, // 动态数据列表
      treeList: [
        { label: '选人', value: 'user' },
        { label: '选部门', value: 'depart' },
        { label: '选行政管理类别', value: 'mantype' },
        { label: '审理信息出庭类型', value: 'std_incourt' },
        { label: '选被申请人类型', value: 'tartype' },
        { label: '行政区划(省、市、县)', value: 'ad' },
        { label: '行政区划(省、市、县、街道)', value: 'ad4' },
        { label: '江西省行政区划(省、市、县、街道)', value: 'ad4jx' }
      ] // 树下拉数据列表
    }
  },

  mutations: {
    SET_ENUM_KEY: (state, enumList) => {
      state.formData.enumList = enumList
    },
    SET_AD4JX: (state) => {
      state.formData.dynamicDataList.ad4jx = json.cascadeData.cityLV4.filter(e=> e.value == 36)
    },
    Add_DYNAMICDATA_KEY: (state, data) => {
      state.formData.dynamicDataList = Object.assign({}, state.formData.dynamicDataList, data)
    }
  },

  actions: {
    GetEnumList ({ commit }) {
      return new Promise((resolve, reject) => {
        queryEnumerationNameList().then(res => {
          if (res.code == 0 && res.data) {
            commit('SET_ENUM_KEY', res.data)
            resolve(res.data)
          }
        })
      }).catch(() => {
        reject('枚举列表获取失败！')
      })
    },
    // 查询枚举值列表
    GetEnumValuesList ({ commit }) {
      return new Promise((resolve, reject) => {
        queryEnumerationValuesList().then(res => {
          if (res.code == 0 && res.data) {
            commit('Add_DYNAMICDATA_KEY', res.data)
            commit('SET_AD4JX')
            resolve(res.data)
          }
        })
      }).catch(() => {
        reject('枚举值列表获取失败！')
      })
    },
    // 树下拉数据值列表
    GetTreeValuesList ({ commit, state }) {
      return new Promise((resolve, reject) => {
        ;['depart', 'user'].forEach(item => {
          return new Promise((resolve, reject) => {
            queryTreeData({ parent: null, type: item })
              .then(res => {
                if (res.code == 0 && res.data) {
                  const data = renderTreeNodes(res.data, item)
                  commit('Add_DYNAMICDATA_KEY', { [item]: data })
                }
              })
              .catch(() => {
                reject('枚举值列表获取失败！', item)
              })
          })
        })
      }).catch(res => {
        reject(res)
      })
    }
  },
  getters: {
    getEnumItem(state) {
      return (enumKey) => {
        return state.formData.dynamicDataList[enumKey] || []
      }
    }
  }
}

export default form
